<template>
	<!-- 差旅编辑补贴明细 -->
	<view>
		<view style="height: 100%;padding-top: 20rpx;padding-bottom: 100rpx;">
			<uni-forms ref="form" :modelValue="entity" label-width="100px">
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="开始日期:" :rules="$rules.handle.DepartureDate" required name="DepartureDate">
						<view @click="DateChange($event, 'DepartureDate')">
							<uni-easyinput v-model="entity.DepartureDate" placeholder="请选择开始日期" :disabled="disabled"
								:inputBorder="false" />
						</view>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="上下午:" :rules="$rules.handle.DepartureAMPM" required name="DepartureAMPM">
						<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
							v-model="entity.DepartureAMPM" :localdata="DepartureAMPMOptions"
							@change="selectOptionsChange($event, 'DepartureAMPM')"
							:disabled="disabled"></uni-data-select>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="结束日期:" :rules="$rules.handle.ArrivalDate" required name="ArrivalDate">
						<view @click="DateChange($event,'ArrivalDate')">
							<uni-easyinput v-model="entity.ArrivalDate" placeholder="请选择结束日期" :disabled="disabled"
								:inputBorder="false" />
						</view>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="上下午:" :rules="$rules.handle.ArrivalAMPM" required name="ArrivalAMPM">
						<uni-data-select :clear="false" style="background-color: #fff;border-radius: 10rpx;"
							v-model="entity.ArrivalAMPM" :localdata="ArrivalAMPMOptions"
							@change="selectOptionsChange($event, 'ArrivalAMPM')" :disabled="disabled"></uni-data-select>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="出差天数:" name="TravelDays">
						<view>
							<uni-easyinput v-model="entity.TravelDays" placeholder="请输入出差天数" :inputBorder="false"
								:disabled="true" />
						</view>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="补贴基数:" name="SubsidyBase">
						<view>
							<uni-easyinput v-model="entity.SubsidyBase" placeholder="请输入补贴基数" :inputBorder="false"
								:disabled="true" />
						</view>
					</uni-forms-item>
				</view>
				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="出差补贴:" name="TravelAllowance">
						<view>
							<uni-easyinput v-model="entity.TravelAllowance" placeholder="请输入出差补贴" :disabled="true"
								:inputBorder="false" />
						</view>
					</uni-forms-item>
				</view>

				<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="摘要:" name="Remark">
						<view>
							<uni-easyinput v-model="entity.Remark" placeholder="请输入摘要" :inputBorder="false"
								:disabled="disabled" type="textarea" />
						</view>
					</uni-forms-item>
				</view>
				<!-- 暂时不要删除 后续根据需求打开 -->
				<!-- 	<view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="附件" name="CustomerName">
						<view>
							这里是附件
						</view>
					</uni-forms-item>
				</view> -->
			</uni-forms>
		</view>
		<view v-if="!disabled" class="submitButton">
			<u-button type="primary" @click="handleSubmitDetailSave">保存</u-button>
		</view>


		<!-- 选择日期 -->
		<u-calendar v-model="isCalendar" :mode="mode" placeholder="请选择日期" @change="calendarChange"></u-calendar>
	</view>
</template>

<script>
	import {
		userInfo
	} from "os";
	import {
		mapState
	} from "vuex";
	// 开始日期上下午
	const DepartureAMPMOptions = [{
			value: 1,
			text: '上午'
		},
		{
			value: 2,
			text: '下午'
		}
	]
	// 结束日期上下午
	const ArrivalAMPMOptions = [{
			value: 1,
			text: '上午'
		},
		{
			value: 2,
			text: '下午'
		}
	]
	export default {
		data() {
			return {
				// 是否展示弹窗
				show: false,
				entity: {},
				// 是否显示日期弹窗
				isCalendar: false,
				// 日期选择
				mode: 'date',
				entity: {},
				disabled: false,
				// 点击的是开始日期还是结束日期
				DateType: "",
				// 开始日期上下午
				DepartureAMPMOptions,
				// 结束日期上下午
				ArrivalAMPMOptions,
				// 补贴明细
				subDetailData: [],
				options: {},
				// 上一页面
				prevPage: null

			}
		},
		computed: {
			...mapState(["UserInfo", "BillTypeOptions", "ExpenseTypeOptions", "InvoiceClassificationOptions",
				"CompayListOptions",
			]),
		},
		onShow() {
			// 1. 获取当前页面栈实例（此时最后一个元素为当前页）
			let pages = getCurrentPages()
			// 2. 上一页面实例
			// 注意是length长度，所以要想得到上一页面的实例需要 -2
			// 若要返回上上页面的实例就 -3，以此类推
			let prevPage = pages[pages.length - 2]
			this.prevPage = prevPage
		},
		onLoad(options) {
			uni.showLoading({
				title: '加载中'
			})
			setTimeout(function() {
				uni.hideLoading()
			}, 500)
			this.options = options
			// 判断是否是详情过来
			if (this.options.type && this.options.type === '查看') {
				this.disabled = true
				uni.setNavigationBarTitle({
					title: '查看补贴明细'
				})
			}
			// this.$nextTick(function() {
			// 	this.$refs.UploadCopy.show = false
			// 	this.$refs.UploadCopy.deletable = true
			// })
			// 
			this.newBillTypeOptions = this.BillTypeOptions
			this.newExpenseTypeOptions = this.ExpenseTypeOptions
			this.newInvoiceClassificationOptions = this.InvoiceClassificationOptions
			this.newCompayListOptions = this.CompayListOptions
			// 传递过来需要编辑的当前行数据
			let data = JSON.parse(options.data)
			this.entity = data.item

			// 补贴基数赋值
			this.entity.SubsidyBase = this.UserInfo.UserInfo.TravelSubsidyBase
			// 单独处理上下午回显  返回的是字符串  需要转换为数字行
			if (this.entity.Id) {
				this.entity.DepartureAMPM = Number(this.entity.DepartureAMPM)
				this.entity.ArrivalAMPM = Number(this.entity.ArrivalAMPM)
			}
			// if (this.entity.ArrivalAMPM === '1') {
			// 	this.entity.ArrivalAMPM = 1
			// } else {
			// 	this.entity.ArrivalAMPM = 2
			// }
			// if (this.entity.DepartureAMPM === '1') {
			// 	this.entity.DepartureAMPM = 1
			// } else {
			// 	this.entity.DepartureAMPM = 2
			// }
			// if (this.entity.ArrivalAMPM === '上午') {
			// 	this.ntity.ArrivalAMPM = 1
			// } else if (this.entity.ArrivalAMPM === '下午') {
			// 	this.entity.ArrivalAMPM = 2
			// }
			// if (this.entity.DepartureAMPM === '上午') {
			// 	this.entity.DepartureAMPM = 1
			// } else if (this.entity.DepartureAMPM === '下午') {
			// 	this.entity.DepartureAMPM = 2
			// }
			// // 处理PC端返回来的上下午回显数据
			// this.entity.ArrivalAMPM = Number(this.entity.ArrivalAMPM)
			// this.entity.DepartureAMPM = Number(this.entity.DepartureAMPM)

			console.log('编辑补贴明细详情渲染', this.entity, )
			// if (this.disabled) {
			// 	console.log('上下午详情-------------------', this.entity)
			// 	// 只有在查看的时候再处理上下午回显数据  避免其他条件出现问题
			// }

		},
		methods: {
			// 求和函数
			sumObjects(arr, key) {
				return arr.reduce((sum, current) => sum + parseFloat(current[key] || 0), 0)
			},
			// 上午下午下拉改变事件
			selectOptionsChange(event, key) {
				console.log('上下午选择', event, key)

				let optionsArr = []

				if (key === 'DepartureAMPM') {
					// 开始日期上下午
					optionsArr = this.DepartureAMPMOptions
				} else {
					//结束日期上下午
					optionsArr = this.ArrivalAMPMOptions
				}
				// 上下午名称
				let Name = optionsArr.filter(item => item.value === event)[0].text
				this.$set(this.entity, key + 'Name', Name)


				let AMPM = 0
				if (this.entity.DepartureAMPM == 1 && this.entity.ArrivalAMPM == 1) {
					AMPM = 0.5
				} else if (this.entity.DepartureAMPM == 2 && this.entity.ArrivalAMPM == 2) {
					AMPM = 0.5
				} else if (this.entity.DepartureAMPM == 1 && this.entity.ArrivalAMPM == 2) {
					AMPM = 1
				} else if (this.entity.DepartureAMPM == 2 && this.entity.ArrivalAMPM == 1) {
					AMPM = 1
				}
				if (this.entity.DepartureDate && this.entity.ArrivalDate) {
					const totalDays = Number(this.getDiffDay(this.entity.DepartureDate, this.entity.ArrivalDate)) + AMPM
					// 自动计算出差补贴   补贴基数*出差天数
					this.entity.TravelAllowance = totalDays * this.entity.SubsidyBase
					// 赋值当前行的出差天数
					this.entity.TravelDays = totalDays
				}
				// // 同时计算应付金额 = 报销总金额 + 出差补贴
				this.entity.PayableAmount = this.entity.ReimburseAmount + this.entity.TravelAllowance
			},
			getDiffDay(date_1, date_2) {
				// 计算两个日期之间的差值
				let totalDays, diffDate
				const myDate_1 = Date.parse(date_1)
				const myDate_2 = Date.parse(date_2)
				// 将两个日期都转换为毫秒格式，然后做差
				diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值
				totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
				// console.log(totalDays)
				return totalDays // 相差的天数
			},
			// 选择日期确定
			calendarChange(event) {

				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
				this.$set(this.entity, this.DateType, event.result);
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************

				let AMPM = 0
				if (this.entity.DepartureAMPM == 1 && this.entity.ArrivalAMPM == 1) {
					AMPM = 0.5
				} else if (this.entity.DepartureAMPM == 2 && this.entity.ArrivalAMPM == 2) {
					AMPM = 0.5
				} else if (this.entity.DepartureAMPM == 1 && this.entity.ArrivalAMPM == 2) {
					AMPM = 1
				} else if (this.entity.DepartureAMPM == 2 && this.entity.ArrivalAMPM == 1) {
					AMPM = 1
				}
				if (this.entity.DepartureDate && this.entity.ArrivalDate) {
					const totalDays = Number(this.getDiffDay(this.entity.DepartureDate, this.entity.ArrivalDate)) + AMPM
					// 自动计算出差补贴   补贴基数*出差天数
					this.entity.TravelAllowance = totalDays * this.entity.SubsidyBase
					// 赋值当前行的出差天数
					this.entity.TravelDays = totalDays
				}
				// if (this.entity.TravelAllowance) {
				// 	// 计算出差补贴总金额
				// 	const TravelAllowanceSummary = this.sumObjects(this.subData, 'TravelAllowance')
				// 	this.entity.TravelAllowance = TravelAllowanceSummary
				// }
				// // 同时计算应付金额 = 报销总金额 + 出差补贴
				// this.entity.PayableAmount = this.entity.ReimburseAmount + this.entity.TravelAllowance

			},
			// 出发日期和到达日期选择
			DateChange(event, key) {
				if (this.disabled) return
				this.DateType = key
				this.isCalendar = true
			},
			// 添加明细保存
			handleSubmitDetailSave() {
				var that = this
				this.$refs.form.validate().then(res => {

					let newEntity = JSON.parse(JSON.stringify(this.entity))
					let pages = getCurrentPages() // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
					let prevPage = pages[pages.length - 2] //上一页页面实例
					console.log('差旅报销添加明细可以保存了', this.entity, prevPage.$vm)
					uni.navigateBack({
						delta: 1,
						success: () => {
							console.log('保存获取上页面方法', prevPage.$vm)
							prevPage.$vm.setDetailData('edit', '补贴',
								newEntity) // 给上一页绑定方法otherFun,传参地址id
						}
					})

				}).catch(err => {})
			},
			init() {
				this.show = true

			},
			openForm(data) {
				this.init()
			},
			close() {
				this.$emit('close')
			}
		}
	}
</script>

<style lang="less" scoped>
	/* 设置 label 的样式 */
	::v-deep.uni-forms-item {
		padding-right: 40rpx !important;

		/* 例如，设置 label 的宽度和对齐方式 */
		.uni-forms-item__label {
			display: flex !important;
			justify-content: flex-end !important;
		}
	}

	// 覆盖uniapp 的 uni-data-select 央视
	::v-deep.uni-select {
		border: none !important;
	}

	// 覆盖uni-data-pirker 样式
	::v-deep.input-value-border {
		border: none !important;
	}

	// 覆盖uviewform表单form-item的下边距
	::v-deep.uni-forms-item {
		margin-bottom: 0 !important;
		border-bottom: 1px solid #EEE;
		padding-top: 20rpx !important;
		padding-bottom: 20rpx !important;
	}

	.submitButton {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 100rpx;
		/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
		height: calc(130rpx + constant(safe-area-inset-bottom));
		/* 直接扩展高度，因为padding-bottom是内边距 */
		height: calc(130rpx + env(safe-area-inset-bottom));
		/* 直接扩展高度 */
		background: #fff;
		padding-top: 10rpx;
		box-sizing: border-box;
		padding-bottom: constant(safe-area-inset-bottom);
		/*兼容 iOS<11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		/* 兼容iOS>= 11.2*/
		border-top: 1px solid #e9e9e9;
		padding-left: 15px;
		padding-right: 15px;
	}
</style>